package com.graduation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.common.domain.dto.PageDTO;
import com.graduation.common.exceptions.BizException;
import com.graduation.mapper.CaseMapper;
import com.graduation.mapper.FavoriteMapper;
import com.graduation.pojo.po.Case;
import com.graduation.pojo.po.LegalDocument;
import com.graduation.pojo.query.CaseQuery;
import com.graduation.pojo.vo.CaseVO;
import com.graduation.service.CaseService;
import com.graduation.service.LegalDocumentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class CaseServiceImpl extends ServiceImpl<CaseMapper, Case> implements CaseService {

    private final LegalDocumentService legalDocumentService;

    private final FavoriteMapper favoriteMapper;

    @Override
    public PageDTO<CaseVO> pageCases(CaseQuery query) {
        // 使用自定义SQL进行联查
        Page<CaseVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<CaseVO> result = baseMapper.selectCaseVOPage(page, query);

        return PageDTO.of(result.getPages(), result.getTotal(), result.getRecords());
    }

    @Override
    public Case getCaseById(Long id) {
        Case caseEntity = getById(id);
        if (caseEntity == null) {
            throw new BizException("案件不存在");
        }
        return caseEntity;
    }

    @Override
    public void saveCase(Case caseEntity) {
        // 检查案件编号是否已存在
        boolean exists = lambdaQuery()
                .eq(Case::getCaseNumber, caseEntity.getCaseNumber())
                .exists();
        if (exists) {
            throw new BizException("案件编号已存在");
        }

        // 验证关联的文档是否存在
        if (caseEntity.getDocumentId() != null) {
            LegalDocument document = legalDocumentService.getById(caseEntity.getDocumentId());
            if (document == null) {
                throw new BizException("关联的法律文档不存在");
            }
        }

        save(caseEntity);
    }

    @Override
    public void updateCase(Case caseEntity) {
        Case existCase = getById(caseEntity.getId());
        if (existCase == null) {
            throw new BizException("案件不存在");
        }

        // 检查案件编号是否被其他案件使用
        if (StrUtil.isNotBlank(caseEntity.getCaseNumber()) &&
                !caseEntity.getCaseNumber().equals(existCase.getCaseNumber())) {
            boolean exists = lambdaQuery()
                    .eq(Case::getCaseNumber, caseEntity.getCaseNumber())
                    .ne(Case::getId, caseEntity.getId())
                    .exists();
            if (exists) {
                throw new BizException("案件编号已存在");
            }
        }

        // 验证关联的文档是否存在
        if (caseEntity.getDocumentId() != null && !caseEntity.getDocumentId().equals(existCase.getDocumentId())) {
            LegalDocument document = legalDocumentService.getById(caseEntity.getDocumentId());
            if (document == null) {
                throw new BizException("关联的法律文档不存在");
            }
        }

        updateById(caseEntity);
    }

    @Override
    public void deleteCase(Long id) {
        Case caseEntity = getById(id);
        if (caseEntity == null) {
            throw new BizException("案件不存在");
        }
        removeById(id);
    }

    @Override
    public List<CaseVO> listHotCase() {
        // 查询收藏数量最高的10个案件
        List<Long> caseIds = favoriteMapper.selectHotCaseTop10();
        if (CollUtil.isEmpty(caseIds)) {
            caseIds = lambdaQuery().orderByDesc(Case::getCreateTime).last("limit 10")
                    .list()
                    .stream()
                    .map(Case::getId).toList();
        }

        // 查询案件信息
        List<Case> cases = listByIds(caseIds);
        if (CollUtil.isEmpty(cases)) {
            return Collections.emptyList();
        }
        int remaining = 10 - cases.size();
        if (remaining > 0) {
            List<Case> list = lambdaQuery()
                    .notIn(Case::getId, caseIds)
                    .orderByDesc(Case::getCreateTime).last("limit " + remaining)
                    .list();
            cases.addAll(list);
        }

        // 查询文档信息
        Set<Long> listDocumentId = cases.stream().map(Case::getDocumentId).collect(Collectors.toSet());
        List<LegalDocument> legalDocuments = legalDocumentService.listByIds(listDocumentId);
        if (CollUtil.isEmpty(legalDocuments)) {
            return Collections.emptyList();
        }
        Map<Long, String> documentMap = legalDocuments.stream()
                .collect(Collectors.toMap(LegalDocument::getId, LegalDocument::getTitle));

        // 组装vo
        List<CaseVO> result = new ArrayList<>(cases.size());
        for (Case item : cases) {
            CaseVO caseVO = new CaseVO();
            BeanUtil.copyProperties(item, caseVO);
            caseVO.setDocumentTitle(documentMap.get(item.getDocumentId()));
            result.add(caseVO);
        }
        return result;
    }

}
